<?php
/**
 * Created by Alan.
 * User: Alan
 * Date: 2018\10\7 0007
 * Time: 6:45
 */

namespace app\lib\exception;


use Exception;
use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;

    public function render(Exception $e)
    {
        if($e instanceof BaseException){
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }
        else
        {
            return parent::render($e);
            //TODO:记录日志
          /*  if(config('app_debug')){
                return parent::render($e);
            }
            else
            {
                $this->code = 500;
                $this->msg = '服务器内部错误';
                $this->errorCode = 999;
                $this->recordErrorLog($e);
            }*/
        }

        $request = Request::instance();
        $errorMsg = [
            'msg' => $this->msg,
            'errorCode' => $this->errorCode,
            'url' => $request->url()
        ];

        return json($errorMsg,$this->code);
    }

    public function recordErrorLog(Exception $e){
        Log::init([
            'type'=> 'File',
            'path' => LOG_PATH,
            'level' => ['error']
        ]);

        Log::record($e->getMessage(),'error');
    }

}